local M = {}
local t = require('utils.table')
local api = vim.api

M.is_floating = function()
    local parent = api.nvim_get_current_win()
    return api.nvim_win_get_config(parent).relative ~= ''
end

M.is_file = function()
    return vim.bo.buftype == ''
end

M.get_window_id_list = function()
    return api.nvim_list_wins()
end

M.get_current_window_id = function()
    return api.nvim_get_current_win()
end

M.close = function(w)
    -- api.nvim_win_close(w,false)
    --
    -- local w2 = api.nvim_get_current_win()
    -- api.nvim_set_option_value('cursorline', true, {win=w2})
    local ok, err = pcall(function()
        if api.nvim_win_is_valid(w) then
            api.nvim_win_close(w, false)
            local w2 = api.nvim_get_current_win()
            if api.nvim_win_is_valid(w2) then
                api.nvim_set_option_value('cursorline', true, {win=w2})
            end
        end
    end) -- silent fail
end

M.close_current = function()
    M.close(M.get_current_window_id())
end

M.has_quickfix_win = function()
    local found = false
    t.foreach(vim.fn.getwininfo(),function(win)
        local buftype = vim.bo[win.bufnr].buftype
        if buftype == 'quickfix' then
            found = true
        end
    end)
    return found
end

M.float2normal = function()
    if not M.is_floating() then
        return
    end
    local fn = require('utils.buf').get_current_filename()
    M.close_current()
    vim.cmd('edit ' .. fn)
end

M.close_current_floating_window = function()
    if not M.is_floating() then
        return
    end
    if vim.bo.buftype == 'prompt' then
        return
    end
    if vim.bo.buftype == 'acwrite' then
	    local k = "\\<c-w>" .. "q"  -- emulate ;q to close win
        require('utils.editor').send_key(k)
        return
    end -- yode
    M.close_current()
end

M.create_mock_floating_window = function()
    local bufnr = api.nvim_create_buf(false, true)
    api.nvim_open_win(bufnr, true, {
        relative = 'editor',
        width = 1,
        height = 1,
        row = vim.o.lines -2, -- right bottom
        col = vim.o.columns -2,
        style = 'minimal',
        border = 'shadow',
    })
end

return M
-- EOP
